﻿using System;
using System.Collections.Generic;
using DotNetOpenAuth.OAuth.ChannelElements;
using RoketSolutions.SP2010.LinkedInWebPart.Common;

namespace RoketSolutions.SP2010.LinkedInWebPart.Authorization
{
    public abstract class TokenSource
    {
        public string ConsumerKey { get; set; }
        public string ConsumerSecret { get; set; }

        public abstract void SetToken(Token token);
        public abstract void RemoveToken(TokenType tokenType);
        public abstract Token GetToken(TokenType tokenType);

        protected readonly Dictionary<TokenType, string> Properties;

        protected TokenSource(string consumerKey, string consumerSecret)
        {
            ConsumerKey = consumerKey;
            ConsumerSecret = consumerSecret;

            Properties = new Dictionary<TokenType, string>
                             {
                                 {TokenType.RequestToken, LinkedInProfileConstants.RequestToken},
                                 {TokenType.AccessToken, LinkedInProfileConstants.AccessToken}
                             };
        }

        public string FindSecret(string token)
        {
            var userToken = GetToken(TokenType.AccessToken);
            if (CheckToken(userToken, token))
            {
                return userToken.Secret;
            }
            userToken = GetToken(TokenType.RequestToken);
            if (CheckToken(userToken, token))
            {
                return userToken.Secret;
            }
            return string.Empty;
        }

        protected static Token CreateToken(TokenType tokenType, string propertyValue)
        {
            if (propertyValue == null || string.IsNullOrEmpty(propertyValue))
            {
                return null;
            }
            var values = propertyValue.Trim().Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            if (values.Length < 2)
            {
                return null;
            }
            return new Token { Key = values[0], Secret = values[1], TokenType = tokenType };
        }

        private bool CheckToken(Token token, string key)
        {
            return token != null && token.Key.Equals(key, StringComparison.OrdinalIgnoreCase);
        }
    }
}
